package com.vimi8.ebb.api.train;

import com.aliyun.oss.OSSClient;
import com.vimi8.ebb.configuration.HttpResponseEntity;
import com.vimi8.ebb.configuration.OAuth2AuthenticationImpl;
import com.vimi8.ebb.dto.TrainMemberDto;
import com.vimi8.ebb.model.*;
import com.vimi8.ebb.model.Error;
import com.vimi8.ebb.service.ElectricityBusinessService;
import com.vimi8.ebb.service.GeoCodingsService;
import com.vimi8.ebb.service.TrainInfoService;
import com.vimi8.ebb.service.TrainMemberService;
import com.vimi8.ebb.util.JxlExcelUtil;
import com.vimi8.ebb.util.PagesUtil;
import com.vimi8.ebb.util.SubStringUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * Created by think on 2016/12/5.
 */
@RestController
@RequestMapping("/train")
public class TrainController
{
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TrainInfoService trainInfoService;
    @Autowired
    private TrainMemberService trainMemberService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ElectricityBusinessService electricityBusinessService;
    @Autowired
    private GeoCodingsService geoCodingsService;
    @Value("${oss.file.region}")
    private String region;
    @Value("${oss.file.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.file.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.file.bucket}")
    private String bucket;
    @ApiOperation(value = "添加培训信息",notes = "添加培训信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/",method = RequestMethod.POST)
    public HttpResponseEntity<String> addTrainInfo(@ApiParam(value = "培训信息",required = true) @RequestBody(required = true) TrainInfo trainInfo){
        int count=0;
        try {
            String addressCode=trainInfo.getTrainAddressCode();
            String orgClass=OAuth2AuthenticationImpl.ClientOrgClass();
           // logger.info("clientId="+clientId+",openId="+openId+"orgClass="+orgClass);
            String clientAddressCode=null;
            // 根据电商办对应的区县 查询区县下的数据
            if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
                clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

            }
            if (StringUtils.isEmpty(addressCode)&&null!=clientAddressCode&&!"".equals(clientAddressCode)){
             //   GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(clientAddressCode);
                addressCode= clientAddressCode;
                logger.info("addressCode="+addressCode);
            }

            trainInfo.setId(UUID.randomUUID().toString());
            trainInfo.setTrainAddressCode(addressCode);
            count=  trainInfoService.insertTrainInfo(trainInfo);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("insert trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }
    @ApiOperation(value = "添加培训信息",notes = "添加培训信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/",method = RequestMethod.PUT)
    public HttpResponseEntity<String> putTrainInfo(@ApiParam(value = "培训信息",required = true) @RequestBody(required = true) TrainInfo trainInfo){
        int count=0;
        try {
            String addressCode=trainInfo.getTrainAddressCode();
            String orgClass=OAuth2AuthenticationImpl.ClientOrgClass();
            // logger.info("clientId="+clientId+",openId="+openId+"orgClass="+orgClass);
            String clientAddressCode=null;
            // 根据电商办对应的区县 查询区县下的数据
            if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
                clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

            }
            if (StringUtils.isEmpty(addressCode)&&null!=clientAddressCode&&!"".equals(clientAddressCode)){
                //   GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(clientAddressCode);
                addressCode= clientAddressCode;
                logger.info("addressCode="+addressCode);
            }
            trainInfo.setTrainAddressCode(addressCode);
            count=  trainInfoService.updateTrainInfo(trainInfo);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("insert trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }

    @ApiOperation(value = "查询培训信息",notes = "查询培训信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/",method = RequestMethod.GET)
    public HttpResponseEntity<Paginator<List<TrainInfo>>> getTrainInfo(@ApiParam(value = "培训标题",required = false) @RequestParam(value = "trainTitle",required = false) String  trainTitle,
                                                                       @ApiParam(value = "培训日期",required = false) @RequestParam(value="startTime",required = false)String startTime,
                                                                       @ApiParam(value = "培训日期",required = false) @RequestParam(value="endTime",required = false)String endTime,
                                                                       @ApiParam(value = "地址code",required = false) @RequestParam(value="addressCode",required = false)String addressCode,
                                                                       @ApiParam(value = "第几页",required = true) @RequestParam(value = "index",required = true)int index,
                                                                       @ApiParam(value = "每页大小",required = true) @RequestParam(value = "size",required = true)int size){
         logger.info("trainTitle="+trainTitle+",startDate="+startTime+",index="+index+",size="+size);
        int count=0;
        PagesUtil pagesUtil=new PagesUtil();
        pagesUtil.setPageSize(size);
        if(index<1){
            pagesUtil.setCurrentPage(1);
        }
        pagesUtil.setCurrentPage(index);
        Paginator<List<TrainInfo>> paginator=null;
        String clientId=OAuth2AuthenticationImpl.clientId();
        String openId=OAuth2AuthenticationImpl.openId();
        String orgClass=OAuth2AuthenticationImpl.ClientOrgClass();
        logger.info("clientId="+clientId+",openId="+openId+"orgClass="+orgClass);
        String clientAddressCode=null;
        // 根据电商办对应的区县 查询区县下的数据
        if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
            clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

        }
        if (StringUtils.isEmpty(addressCode)&&null!=clientAddressCode&&!"".equals(clientAddressCode)){
            GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(clientAddressCode);
            addressCode= SubStringUtil.separateGeoCodeByProduct(geoCodings.getId(),geoCodings.getRegionLever()+1+"");
            logger.info("addressCode="+addressCode);
        }

        try {
            int total=trainInfoService.queryTrainInfoCount(trainTitle,startTime,endTime,addressCode);
            logger.info("total="+total);
            pagesUtil.setTotalCount(total);
            List<TrainInfo> trainInfos=trainInfoService.queryTraInfoList(trainTitle,startTime,endTime,addressCode,(pagesUtil.getCurrentPage()-1)*size,size);
            logger.info("trainInfos="+trainInfos);
            paginator=new Paginator<List<TrainInfo>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),trainInfos);
            return new HttpResponseEntity<Paginator<List<TrainInfo>>>(paginator,HttpStatus.OK);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("query trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ApiOperation(value = "查询培训信息",notes = "查询培训信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/{id}",method = RequestMethod.GET)
    public HttpResponseEntity<TrainInfo> getTrainInfoById(@ApiParam(value = "每页大小",required = true) @PathVariable(value = "id",required = true)String id){
        logger.info("id="+id);

        try {
            TrainInfo trainInfo=trainInfoService.queryTraInfoById(id);
            return new HttpResponseEntity<TrainInfo>(trainInfo,HttpStatus.OK);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("query trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @ApiOperation(value = "删除培训信息",notes = "删除培训信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/{id}",method = RequestMethod.DELETE)
    public HttpResponseEntity<String> deleteTrainInfoById(@ApiParam(value = "每页大小",required = true) @PathVariable(value = "id",required = true)String id){
        logger.info("id="+id);
        int count=0;
        try {
            count=trainInfoService.deleteTraInfoById(id);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("query trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ApiOperation(value = "添加培训学员信息",notes = "添加培训学员信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/member/",method = RequestMethod.POST)
    public HttpResponseEntity<String> getTestData(@ApiParam(value = "培训学员信息",required = true) @RequestBody(required = true) TrainMember trainMember){
        int count=0;
        try {
            count=  trainMemberService.insertTrainMember(trainMember);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("insert trainMember error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }
    @ApiOperation(value = "查询培训学员信息",notes = "查询培训学员信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/all/",method = RequestMethod.GET)
    public HttpResponseEntity<List<TrainInfo>> getAllTrainInfo(){
        List<TrainInfo> trainInfos=new ArrayList<>();

        try {
            trainInfos=  trainInfoService.queryTraInfoAllList();
            logger.info("trainInfos="+trainInfos);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("query trainInfos error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<List<TrainInfo>>(trainInfos,HttpStatus.OK);
    }
    @ApiOperation(value = "导入培训信息",notes = "导入培训信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/import/",method = RequestMethod.POST)
    public HttpResponseEntity<String> importTrainInfoEecel(@RequestParam("file") MultipartFile file) {
//            public Response(boolean error, int errorType, String errorMessage) {
        ;logger.info("upload file param="+file.toString());
        if(file==null){
            return new HttpResponseEntity("上传文件不能为空！请重新选择导入文件",HttpStatus.HTTP_VERSION_NOT_SUPPORTED);
        }
        HttpResponseEntity<String> response=null;
        List<TrainInfo> trainInfos=new ArrayList<TrainInfo>();
        trainInfos=  JxlExcelUtil.readTrainInfoExcel(file);
        int count=0;
        try {
            count=  trainInfoService.batchTrainInfo(trainInfos);
//
            response=new HttpResponseEntity(count+"",HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getMessage());
            response=new HttpResponseEntity("上传文件出错 "+e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return response;
    }
    @ApiOperation(value = "缓存trainId", notes = "缓存trainId.", response = String.class, tags = {"培训信息",})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,用户信息", response = String.class),
            @ApiResponse(code = 200, message = "失败,返回消息", response = String.class)})
    @RequestMapping(value = "/info/cache/",
            method = RequestMethod.GET)
    public HttpResponseEntity<String> qrCodeCache( @ApiParam(value = "缓存trainId", required = true) @RequestParam(value="trainId",required = true) String trainId) {

        logger.info(" trainId="+trainId);
        try {
            redisTemplate.opsForValue().set("trainId-"+trainId,trainId);
        } catch (Exception e) {
            return new HttpResponseEntity<>("cache token error", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>("cache token success", HttpStatus.OK);
    }

    @ApiOperation(value = "导入培训学员信息",notes = "导入培训学员信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/member/import/",method = RequestMethod.POST)
    public HttpResponseEntity<String> importTrainMemberEecel(@RequestParam("file") MultipartFile file) {
//            public Response(boolean error, int errorType, String errorMessage) {
        HttpResponseEntity<String> response=null;
        ;logger.info("upload file param="+file.toString());
       String fileName= file.getOriginalFilename();
        String suffix="";
        if(!StringUtils.isEmpty(fileName)&&fileName.contains(".")){
            suffix=  suffix=fileName.substring(fileName.indexOf(".")+1,fileName.length());
        }
        String trainId=null;
        try {
            trainId = (String) redisTemplate.opsForValue().get("trainId-"+trainId);
            if(!StringUtils.isEmpty(trainId)){
                redisTemplate.delete("trainId-"+trainId);
            }
            ;logger.info("trainId="+trainId);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        if(file==null){
            return new HttpResponseEntity("上传文件不能为空！请重新选择导入文件",HttpStatus.HTTP_VERSION_NOT_SUPPORTED);
        }
      //  String imageUrl="";//http://vimi8-dev.oss-cn-shenzhen.aliyuncs.com/7ED9FF8026C162881EA1EF50951D58D1.jpg
        //如果上传的是图片则 上传图片到阿里云存储服务
        if(!StringUtils.isEmpty(fileName)&&(fileName.toLowerCase().contains("jpg")||fileName.toLowerCase().contains("png"))){
            // endpoint以杭州为例，其它region请按实际情况填写
         //   String endpoint = "http://"+region;
             // accessKey请登录https://ak-console.aliyun.com/#/查看
        // 创建OSSClient实例
            logger.info("region="+region+",accessKeyId="+accessKeyId+",accessKeySecret="+accessKeySecret);
            // "http://oss-cn-hangzhou.aliyuncs.com";

            OSSClient ossClient = new OSSClient("http://"+region+".aliyuncs.com", accessKeyId, accessKeySecret);

         // 上传文件流
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
            } catch (Exception e) {
                logger.error(e.getMessage());
                response=new HttpResponseEntity("上传文件出错 "+e.getMessage(),HttpStatus.HTTP_VERSION_NOT_SUPPORTED);
            }
          String imageUrl=UUID.randomUUID().toString()+"."+suffix;
            ossClient.putObject(bucket, imageUrl, inputStream);
        // 关闭client
            ossClient.shutdown();
            TrainMember trainMember=new TrainMember();
            trainMember.setId(UUID.randomUUID().toString());
            trainMember.setTrainId(trainId);
            trainMember.setMemberImage("http://"+bucket+"."+region+".aliyuncs.com/"+imageUrl);
            logger.info("imageUrl="+imageUrl);
            try {
                trainMemberService.insertTrainMember(trainMember);
            } catch (Exception e) {
                logger.error(e.getMessage());
                response=new HttpResponseEntity("插入学员信息异常 "+e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
                return response;
            }
            response=new HttpResponseEntity("success",HttpStatus.OK);
            return response;
        }


        List<TrainMember> trainInfos=new ArrayList<TrainMember>();
        trainInfos=  JxlExcelUtil.readTrainMmberExcel(file,trainId);
        redisTemplate.delete("trainId");
        int count=0;
        try {
           count= trainMemberService.batchTrainMember(trainInfos);

            response=new HttpResponseEntity(count+"",HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getMessage());
            response=new HttpResponseEntity("上传文件出错 "+e.getMessage(),HttpStatus.HTTP_VERSION_NOT_SUPPORTED);
        }
        return response;
    }


    @ApiOperation(value = "查询培训信息",notes = "查询培训信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/member/",method = RequestMethod.GET)
    public HttpResponseEntity<Paginator<List<TrainMemberDto>>> getTrainMemberDto(
            @ApiParam(value = "学员名字",required = false) @RequestParam(value = "memberName",required = false) String  memberName,
            @ApiParam(value = "培训标题",required = false) @RequestParam(value = "trainTitle",required = false) String  trainTitle,
                                                                            @ApiParam(value = "培训日期",required = false) @RequestParam(value="trainDate",required = false)String trainDate,
                                                                            @ApiParam(value = "地址code",required = false) @RequestParam(value="addressCode",required = false)String addressCode,
                                                                            @ApiParam(value = "第几页",required = true) @RequestParam(value = "index",required = true)int index,
                                                                            @ApiParam(value = "每页大小",required = true) @RequestParam(value = "size",required = true)int size){
        logger.info("trainTitle="+trainTitle+",trainDate="+trainDate+",index="+index+",size="+size);
        int count=0;
        PagesUtil pagesUtil=new PagesUtil();
        pagesUtil.setPageSize(size);
        if(index<1){
            pagesUtil.setCurrentPage(1);
        }
        pagesUtil.setCurrentPage(index);
        Paginator<List<TrainMemberDto>> paginator=null;
        String clientId=OAuth2AuthenticationImpl.clientId();
        String openId=OAuth2AuthenticationImpl.openId();
        String orgClass=OAuth2AuthenticationImpl.ClientOrgClass();
        logger.info("clientId="+clientId+",openId="+openId+"orgClass="+orgClass);
        String clientAddressCode=null;
        // 根据电商办对应的区县 查询区县下的数据
        if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
             clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

        }
        if (StringUtils.isEmpty(addressCode)&&null!=clientAddressCode&&!"".equals(clientAddressCode)){
            GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(clientAddressCode);
            addressCode= SubStringUtil.separateGeoCodeByProduct(geoCodings.getId(),geoCodings.getRegionLever()+1+"");
            logger.info("addressCode="+addressCode);
        }
        try {
            int total=trainMemberService.queryTrainMemeberCount(memberName,trainTitle,trainDate,addressCode);
            logger.info("total="+total);
            pagesUtil.setTotalCount(total);
            List<TrainMemberDto> trainMemberDtos=trainMemberService.queryTraMemberList(memberName,trainTitle,trainDate,addressCode,(pagesUtil.getCurrentPage()-1)*size,size);
            logger.info("trainMemberDtos="+trainMemberDtos);
            paginator=new Paginator<List<TrainMemberDto>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),trainMemberDtos);
            return new HttpResponseEntity<Paginator<List<TrainMemberDto>>>(paginator,HttpStatus.OK);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("query trainmember error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /*导出培训信息excel*/
    @ApiOperation(value = "导出培训信息",notes = "导出培训信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/export/", method = RequestMethod.GET)
    public void exportTrainInfoEecel(HttpServletResponse httpServletResponse,
                                     @ApiParam(value = "培训标题",required = false) @RequestParam(value = "trainTitle",required = false) String  trainTitle,
                                     @ApiParam(value = "培训日期",required = false) @RequestParam(value="startTime",required = false)String startTime,
                                     @ApiParam(value = "培训结束日期",required = false) @RequestParam(value="endTime",required = false)String endTime,
                                     @ApiParam(value = "地址code",required = false) @RequestParam(value="addressCode",required = false)String addressCode) {
        logger.info("requestUrl="+"/train/info/export/");
        List<TrainInfo> trainInfoList=new ArrayList<TrainInfo>();
        HttpResponseEntity<byte[]> result=new HttpResponseEntity<byte[]>(HttpStatus.OK);
        String orgClass=OAuth2AuthenticationImpl.ClientOrgClass();
        String clientAddressCode=null;
        // 根据电商办对应的区县 查询区县下的数据
        if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
            clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

        }
        if (StringUtils.isEmpty(addressCode)&&null!=clientAddressCode&&!"".equals(clientAddressCode)){
            GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(clientAddressCode);
            addressCode= SubStringUtil.separateGeoCodeByProduct(geoCodings.getId(),geoCodings.getRegionLever()+1+"");
            logger.info("addressCode="+addressCode);
        }
       trainInfoList=trainInfoService.queryTraInfoListForExcel(trainTitle,startTime,endTime,addressCode);
        String[] headers={"培训标题","培训内容","培训类型","培训时间","培训地址","培训老师","性别","电话","成员类型","参与人数"};
        String[] methods={"getTrainTitle","getTrainContent","getTrainType","getTrainDate","getTrainAddress","getTrainTeacher","getSex","getPhone","getTrainObject","getTrainPeoples"};

        try {
            String filename="培训信息";
            String filepath="./"+filename;

            // filename = new String(filename.getBytes(),"iso-8859-1");

            JxlExcelUtil.writeExcelObject(filepath,headers,methods,trainInfoList,httpServletResponse);

            InputStream inStream = new FileInputStream(filepath);
            httpServletResponse.reset();
            httpServletResponse.setContentType("application/msexcel;charset=UTF-8");
            //new String(("attachment;filename="+"error.xls").getBytes("GB2312")
            // filename="+new String((titlename).getBytes("gbk"),"iso8859-1")+".xls");
            httpServletResponse.addHeader("Content-Disposition",
                    "attachment;   filename=\"" + new String((filename).getBytes("gbk"),"iso8859-1")+ ".xls\"");
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                httpServletResponse.getOutputStream().write(b, 0, len);
            }
            inStream.close();

        } catch (Exception e) {
          logger.info(e.getMessage());
        }

    }
    /*导出培训成员信息excel*/
        /*导出培训信息excel*/
    @ApiOperation(value = "导出培训学员信息",notes = "导出培训学员信息",response = String.class,tags = {"培训信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/member/export/", method = RequestMethod.GET)
    public void exportTrainMemberEecel(HttpServletResponse httpServletResponse,
                                     @ApiParam(value = "培训标题",required = false) @RequestParam(value = "trainTitle",required = false) String  trainTitle,
                                     @ApiParam(value = "培训日期",required = false) @RequestParam(value="trainDate",required = false)String trainDate,
                                     @ApiParam(value = "地址code",required = false) @RequestParam(value="addressCode",required = false)String addressCode) {
        logger.info("requestUrl="+"/train/member/export/");
        List<TrainMemberDto> trainMemberDtos=new ArrayList<TrainMemberDto>();
        //aidPeopleArrayList=  aidPeopleService.getAidPeopleInfo();
        HttpResponseEntity<byte[]> result=new HttpResponseEntity<byte[]>(HttpStatus.OK);
        trainMemberDtos=trainMemberService.queryTraMemberListForExcel(trainTitle,trainDate,addressCode);
        String[] headers={"培训标题","培训内容","名字","性别","电话","创业方向","培训效果评价","地址","类型"};
        String[] methods={"getTrainTitle","getTrainContent","getMemberName","getMemberSex","getMemberPhone","getEnterOrientation","getTrainEvaluate","getMemberAddress","getMemberType"};
        // String excelName = "贫困户基本信息.xls";
        // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开

        try {
            String filename="培训学员信息";
            String filepath="./"+filename;

            // filename = new String(filename.getBytes(),"iso-8859-1");

            JxlExcelUtil.writeExcelObject(filepath,headers,methods,trainMemberDtos,httpServletResponse);

            InputStream inStream = new FileInputStream(filepath);
            httpServletResponse.reset();
            httpServletResponse.setContentType("application/msexcel;charset=UTF-8");
            //new String(("attachment;filename="+"error.xls").getBytes("GB2312")
            // filename="+new String((titlename).getBytes("gbk"),"iso8859-1")+".xls");
            httpServletResponse.addHeader("Content-Disposition",
                    "attachment;   filename=\"" + new String((filename).getBytes("gbk"),"iso8859-1")+ ".xls\"");
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                httpServletResponse.getOutputStream().write(b, 0, len);
            }
            inStream.close();


        } catch (Exception e) {
            logger.info(e.getMessage());
        }

    }

    @ApiOperation(value = "批量删除培训信息", notes = "批量删除培训信息.参数形如：'xxxx','xxxx','xxxx'", response = String.class,
            tags = {"培训信息",})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 200, message = "失败,返回消息", response = String.class)})
    @RequestMapping(value = "/info/deleteSelectedAll/",
            method = RequestMethod.DELETE)
    HttpResponseEntity<String> deleteSelectedAllTrainInfo(
            @ApiParam(value = "物流信息ids", required = true) @RequestBody( required = true) String ids
    ){
        int count = 0;
        try {
            count = trainInfoService.deleteTraInfoBySelectedIds(ids);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @ApiOperation(value = "批量删除培训学员信息", notes = "批量删除培训学员信息.参数形如：'xxxx','xxxx','xxxx'", response = String.class,
            tags = {"培训信息",})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 200, message = "失败,返回消息", response = String.class)})
    @RequestMapping(value = "/member/deleteSelectedAll/",
            method = RequestMethod.DELETE)
    HttpResponseEntity<String> deleteSelectedAllTrainMemInfo(
            @ApiParam(value = "培训学员信息ids", required = true) @RequestBody( required = true) String ids
    ){
        int count = 0;
        try {
            count = trainMemberService.deleteTraMenberBySelectedIds(ids);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }
}
